package com.wangwei.modules.utils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JspUtil {
    //正则字符串,${*}格式
    private static final String REGEX = "\\$\\{[A-Za-z0-9_]*\\}";

    /**
     * 翻译jsp
     * @param jsp
     * @param attribute
     * @return
     */
    public static String translateJSP(String jsp, Map attribute) {
        Set<String> keys = getSymbol(jsp);
        return assembleContent(jsp, keys, attribute);
    }

    /**
     * 提取${}格式的表达式
    <pre>
    pro..
        in:
            "we12e1${aavvcc},sss${aavvcc}sdqweqe${aa}"
        out:
            ${aavvcc}
            ${aavvcc}
            ${aa}
        format:
            [${aa}, ${aavvcc}]
    </pre>
      * @param formatStr
      * @return
     */
    protected static Set<String> getSymbol(String formatStr) {
        Set<String> set = new HashSet<String>();
        Pattern pat = Pattern.compile(REGEX);
        Matcher mat = pat.matcher(formatStr);
        while (mat.find()) {
            String temp = mat.group();
            set.add(temp.substring(2, temp.length() - 1));
        }
        return set;
    }

    /**
     * 正则替换格式化字符串
     * <pre>
     * in:
     *         attribute.put("aavvcc", "hello");
     *         attribute.put("aa", "'dddddddd'");
     *         attribute.put("cc", "'dddddddd'");
     *         String format = "we12e1${aavvcc},sss${aavvcc}sdqweqe${aa}";
     * out:
     *         we12e1hello,ssshellosdqweqe'dddddddd'
     * </pre>
     * @param format 格式化资费串
     * @param 模板字段
     * @param attribute
     * @return 替换好的内容
     */
    @SuppressWarnings("rawtypes")
    protected static String assembleContent(String format, Set<String> keys, Map attribute) {
        //获取${*}格式的内容
        for (String key : keys) {
            format = format.replace("${" + key + "}", attribute != null ? attribute.containsKey(key) ? attribute.get(key).toString() : "" : "");
        }
        return format;
    }
}
